package com.gitee.wsl.doc.sample.rss.utils

import com.gitee.wsl.doc.sample.rss.utils.toPrefixNamedElement
import com.gitee.wsl.doc.xml.XmlPullParser
import com.gitee.wsl.doc.xml.lowercaseName
import com.gitee.wsl.doc.xml.lowercasePrefix

/**
 * Utility function to return a lowercase rss [com.gitee.wsl.doc.sample.rss.utils.PrefixNamedHolder]
 */
internal fun String.toPrefixNamedElement(): com.gitee.wsl.doc.sample.rss.utils.PrefixNamedHolder = split(delimiters = arrayOf(":"), false, 2).let {
    return if (it.size > 1) {
        _root_ide_package_.com.gitee.wsl.doc.sample.rss.utils.ParseRSSElement(it[0], it[1])
    } else {
        _root_ide_package_.com.gitee.wsl.doc.sample.rss.utils.ParseRSSElement("", it[0])
    }
}

/**
 * Utility function to combine and return rss element name and prefix
 */
internal fun XmlPullParser.getRSSElement(nsAware: Boolean = false): com.gitee.wsl.doc.sample.rss.utils.ParseRSSElement {
    return if (nsAware) {
        _root_ide_package_.com.gitee.wsl.doc.sample.rss.utils.ParseRSSElement(lowercasePrefix(), lowercaseName())
    } else {
        lowercaseName().toPrefixNamedElement() as com.gitee.wsl.doc.sample.rss.utils.ParseRSSElement
    }
}

/**
 * Utility function to combine and return rss attribute name and prefix
 */
fun XmlPullParser.getRSSAttributeElement(index: Int, nsAware: Boolean = false): com.gitee.wsl.doc.sample.rss.utils.ParseRSSAttribute {
    val fxPrefix: () -> String = { (getAttributePrefix(index) ?: "").lowercase() }
    val fxName: () -> String = { (getAttributeName(index) ?: "").lowercase() }
    val fxValue: () -> String = { (getAttributeValue(index) ?: "") }
    return if (nsAware) {
        _root_ide_package_.com.gitee.wsl.doc.sample.rss.utils.ParseRSSAttribute(fxPrefix(), fxName(), fxValue())
    } else {
        val holder = fxName().toPrefixNamedElement()
        _root_ide_package_.com.gitee.wsl.doc.sample.rss.utils.ParseRSSAttribute(holder.prefix, holder.name, fxValue())
    }
}


/**
 * Utility function to get last value of a [LinkedHashMap]
 */
internal fun <K, T> LinkedHashMap<K, T>.lastValue() = values.last()

/**
 * Combine current namespace string with supplied local name
 */
internal fun String.buildRSSName(localName: String) = "$this:$localName"

/**
 * Combine prefix namespace (if any) with the local name
 */
internal fun com.gitee.wsl.doc.sample.rss.utils.ParseRSSElement.buildRSSName() = if (hasNamespace()) "$prefix:$name" else name
